package com.rongshu.view.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.BitmapUtils;
import com.rongshu.utils.Constant;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.GlideUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.home.contract.EditDaySignView;
import com.rongshu.view.home.entity.DaySignDetailsResponse;
import com.rongshu.view.home.entity.DaySignInfo;
import com.rongshu.view.home.presenter.EditDaySignPresenter;
import com.rongshu.widget.BanyanDialog;
import com.umeng.socialize.UMShareAPI;
import com.utils.DensityUtil;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.titlebar.OnKeyboardListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2019/2/18.
 * description：编辑日签页面
 */
public class EditDaySignActivity extends BaseActivity<EditDaySignPresenter> implements EditDaySignView {

    @BindView(R.id.head_middle)
    TextView headMiddle;
    @BindView(R.id.day_sign_img)
    ImageView daySingImg;
    @BindView(R.id.sign_content)
    EditText signContent;
    @BindView(R.id.sign_author_right)
    TextView signAuthorRight;
    @BindView(R.id.bottom_option)
    LinearLayout bottomOption;
    @BindView(R.id.zoom_content)
    RelativeLayout zoomContent;
    @BindView(R.id.sign_date)
    TextView shareDataLayout;
    @BindView(R.id.zoom_header)
    RelativeLayout zoomHead;
    @BindView(R.id.change_img)
    RelativeLayout changeImg;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.content_length)
    TextView contentLength;
    @BindView(R.id.share_layout)
    RelativeLayout shareLayout;
    private boolean isEdit = false;//是否对日签内容进行过编辑
    private int REQUEST_CODE_PICTURE = 100;
    //permission
    private String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    private String picturePath;
    private int signId;
    private int type; //1制作，2官方日签
    private String defaultImgUrl;
    private DaySignDetailsResponse.ResponseBean bean;//接口返回该日签详情
    private boolean isSaveLocal = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersionBar.keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE).setOnKeyboardListener(new OnKeyboardListener() {
            @Override
            public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                bottomOption.setVisibility(isPopup ? View.GONE : View.VISIBLE);
                signContent.setCursorVisible(isPopup);
                contentLength.setVisibility(isPopup ? View.VISIBLE : View.GONE);
            }
        });
        immersionBar.init();
    }


    @Override
    protected int initLayout() {
        return R.layout.activity_day_sign;
    }

    @Override
    protected void initView() {
        headMiddle.setText("制作日签");
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        signId = intent.getIntExtra(Constant.INTENT_DATA, 0);
        type = intent.getIntExtra(Constant.INTENT_TYPE, 1);
        signAuthorRight.setText(type == Constant.DAY_SIGN_AUTHOR ? UserInfoUtils.getBiName() : "榕书");
        setPresenter(new EditDaySignPresenter(this), this);
        presenter.getDaySignInfo(type, signId);
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_PICTURE) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (!TextUtils.isEmpty(selectList.get(0).getCutPath())) {
                    picturePath = selectList.get(0).getCutPath();
                    presenter.bindImg(daySingImg, picturePath);
                    signAuthorRight.setText(UserInfoUtils.getBiName());
                    isEdit = true;
                    handler.sendEmptyMessage(HANDLER_MSG_SCROLL_CODE);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        PictureFileUtils.deleteCacheDirFile(this);
        handler.removeCallbacksAndMessages(null);
    }

    @OnClick({R.id.head_left, R.id.change_img, R.id.save_sign, R.id.share_sign, R.id.day_sign_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                showKeyboard(false);
                onBackPressed();
                break;
            case R.id.change_img:
                presenter.getPicture(REQUEST_CODE_PICTURE);
                break;
            case R.id.save_sign:
                if (!XXPermissions.isHasPermission(this, mPermissionList)) {
                    XXPermissions.with(this).permission(mPermissionList).request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            saveImgDialog();
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                        }
                    });
                } else {
                    saveImgDialog();
                }
                break;
            case R.id.share_sign:
                if (bean != null){
                    DaySignInfo.ResponseBean daySignBean = new DaySignInfo.ResponseBean();
                    daySignBean.setDailyDate(bean.getDailyDate());
                    daySignBean.setImgUrl(TextUtils.isEmpty(picturePath) ? bean.getImgUrl() : picturePath);
                    daySignBean.setImgExplain(bean.getImgExplain());
                    daySignBean.setDailyContent(signContent.getText().toString());
                    daySignBean.setIsSystem(isEdit ? 1 : 2);//1制作，2官方日签
                    Intent intent = new Intent(this, ShareDaySignActivity.class);
                    intent.putExtra(Constant.INTENT_DATA, daySignBean);
                    startActivity(intent);
                }
                break;
            case R.id.day_sign_img:
                showKeyboard(false);
                break;
        }
    }

    private void saveImgDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("保存");
        builder.setContent("是否同时保存到相册");
        builder.setLeft("否");
        builder.setRight("是");
        final BanyanDialog dialog = builder.create();
        dialog.show();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                isSaveLocal = false;
                dialog.dismiss();
                showPromptDialog();
            }

            @Override
            public void rightClickListener() {
                isSaveLocal = true;
                dialog.dismiss();
                showPromptDialog();
            }
        });
    }

    private void showPromptDialog() {
        if (TextUtils.isEmpty(picturePath)) {
            if (!TextUtils.isEmpty(defaultImgUrl)) {
                showLoading(true);
                uploadImgSuccess(defaultImgUrl);
            } else {
                toast("请选择一张图片");
            }
        } else {
            showLoading(true);
            presenter.uploadTopImg(picturePath);
        }
    }

    private Bitmap dealWithBitmap() {
        Bitmap head = BitmapUtils.loadBitmapFromView(shareLayout);
        Bitmap foot = BitmapFactory.decodeResource(getResources(), R.drawable.share_term_table_footer);
        Bitmap bitmap = presenter.resetBitmapSize(foot,
                DensityUtil.getScreenWidth(EditDaySignActivity.this), (int) getResources().getDimension(R.dimen.dd_dimen_150px));
        Bitmap shareImg = BitmapUtils.toConformBitmap(head, bitmap);
        return shareImg;
    }

    @Override
    public void onBackPressed() {
        if (shareDataLayout.getVisibility() == View.VISIBLE) {
            shareDataLayout.setVisibility(View.GONE);
        }
        if (isEdit) {
            presenter.showHintDialog();
        } else {
            finishActivity();
        }
    }

    @Override
    public void uploadImgSuccess(String imgUrl) {
        /**
         * 如果是官方日签，该操作为 制作日签；如果是用户日签，该操作为 编辑日签
         */
        PictureFileUtils.deleteCacheDirFile(this);
        if (type == Constant.DAY_SIGN_AUTHOR) {
            presenter.editDaySign(signId, signContent.getText().toString(),
                    signAuthorRight.getText().toString(), imgUrl);
        } else {
            presenter.makeDaySign(signContent.getText().toString(),
                    signAuthorRight.getText().toString(), imgUrl);
        }
        if (isSaveLocal) {
            //为保存到本地相册做准备，显示时间/隐藏更换图片的入口
            shareDataLayout.setVisibility(View.VISIBLE);
            changeImg.setVisibility(View.GONE);
        }
    }

    @Override
    public void saveDaySignSuccess() {
        isEdit = false;
        //保存到本地
        Bitmap bitmap = dealWithBitmap();
        if (isSaveLocal) {
            BitmapUtils.saveImageToGallery(this, bitmap);
            toast("保存成功");
        } else {
            toast("已保存至我的日签");
        }
        handler.sendEmptyMessageDelayed(HANDLER_MSG_SAVE_SIGN, 1000);
    }

    @Override
    public void callBackDaySignResponse(DaySignDetailsResponse.ResponseBean bean) {
        this.bean = bean;
        defaultImgUrl = bean.getImgUrl();
        GlideUtils.loadImageView(this, daySingImg, bean.getImgUrl());
        signContent.setText(bean.getDailyContent());
        //让光标停留在最后
        signContent.setSelection(bean.getDailyContent().length());
        contentLength.setText(bean.getDailyContent().length() + "/2000");
        String today = DateUtils.getToday("yyyy年MM月dd日");
        shareDataLayout.setText(today + " " + DateUtils.getTodayWeek());
        signContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                signAuthorRight.setText(UserInfoUtils.getBiName());
                contentLength.setText(s.toString().length() + "/2000");
                isEdit = true;
            }
        });
        handler.sendEmptyMessage(HANDLER_MSG_SCROLL_CODE);
    }

    @Override
    public void saveFaild() {
        showLoading(false);
    }

    @Override
    public void finishActivity() {
        PictureFileUtils.deleteCacheDirFile(this);
        finish();
    }

    static final int HANDLER_MSG_SCROLL_CODE = 111;//scrollview滑动到底部
    static final int HANDLER_MSG_SAVE_SIGN = 222;//保存日签到本地
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.what;
            switch (code) {
                case HANDLER_MSG_SCROLL_CODE:
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    break;
                case HANDLER_MSG_SAVE_SIGN:
                    shareDataLayout.setVisibility(View.GONE);
                    changeImg.setVisibility(View.VISIBLE);
                    showLoading(false);
                    break;
            }
        }
    };
}
